<template>
  <div class="allocations">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>🏠 宿舍分配管理</span>
          <div class="header-actions">
            <el-button @click="refreshAllocations" :loading="loading">
              刷新
            </el-button>
            <el-button type="success" @click="showAutoAllocationModal = true">
              自动分配
            </el-button>
            <el-button type="primary" @click="showManualAllocationModal = true">
              手动分配
            </el-button>
      </div>
    </div>
      </template>

      <!-- 搜索和筛选 -->
        <div class="search-section">
        <el-input
          v-model="searchQuery"
              placeholder="搜索学生姓名、学号..."
          style="width: 300px; margin-right: 16px;"
          clearable
        >
          <template #prefix>
          </template>
        </el-input>
        <el-select v-model="statusFilter" placeholder="全部状态" style="width: 120px; margin-right: 16px;" clearable>
          <el-option label="未分配" value="unallocated" />
          <el-option label="已分配" value="allocated" />
          <el-option label="待确认" value="pending" />
        </el-select>
        <el-select v-model="gradeFilter" placeholder="全部年级" style="width: 120px;" clearable>
          <el-option label="2021级" value="2021" />
          <el-option label="2022级" value="2022" />
          <el-option label="2023级" value="2023" />
          <el-option label="2024级" value="2024" />
        </el-select>
      </div>

      <el-table :data="filteredAllocations" style="width: 100%" v-loading="loading">
        <el-table-column label="学生信息" min-width="200">
          <template #default="{ row }">
                <div class="student-info">
              <div class="student-name">{{ row.student.name }}</div>
              <div class="student-id">{{ row.student.studentId }}</div>
                </div>
          </template>
        </el-table-column>
        <el-table-column label="年级" width="100">
          <template #default="{ row }">
            {{ row.student.grade }}级
          </template>
        </el-table-column>
        <el-table-column label="专业" width="150">
          <template #default="{ row }">
            {{ row.student.major }}
          </template>
        </el-table-column>
        <el-table-column label="分配状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="房间信息" width="150">
          <template #default="{ row }">
            <div v-if="row.room" class="room-info">
              <div class="room-number">{{ row.room.number }}</div>
              <div class="bed-number">{{ row.bed?.number || '-' }}</div>
                </div>
            <el-text v-else type="info">未分配</el-text>
          </template>
        </el-table-column>
        <el-table-column label="分配时间" width="150">
          <template #default="{ row }">
            <el-text v-if="row.allocatedAt" type="info">{{ formatDate(row.allocatedAt) }}</el-text>
            <el-text v-else type="info" style="color: #999;">-</el-text>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="viewAllocation(row)"
              v-if="row.status === 'allocated'"
            >
              查看
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="allocateStudent(row)"
              v-if="row.status === 'unallocated'"
            >
              分配
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="reallocateStudent(row)"
              v-if="row.status === 'allocated'"
            >
              调整
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="cancelAllocation(row)"
              v-if="row.status === 'allocated'"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 自动分配对话框 -->
    <el-dialog v-model="showAutoAllocationModal" title="🤖 自动分配宿舍" width="600px">
      <el-form :model="autoAllocationForm" label-width="100px">
        <el-form-item label="分配策略">
          <el-select v-model="autoAllocationForm.strategy" placeholder="选择分配策略" style="width: 100%;">
            <el-option label="随机分配" value="random" />
            <el-option label="按年级分配" value="grade" />
            <el-option label="按专业分配" value="major" />
            <el-option label="按偏好分配" value="preference" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标年级">
          <el-select v-model="autoAllocationForm.grade" placeholder="选择年级" style="width: 100%;" clearable>
            <el-option label="2021级" value="2021" />
            <el-option label="2022级" value="2022" />
            <el-option label="2023级" value="2023" />
            <el-option label="2024级" value="2024" />
          </el-select>
        </el-form-item>
        <el-form-item label="房间类型偏好">
          <el-checkbox-group v-model="autoAllocationForm.roomTypes">
            <el-checkbox label="standard">标准间</el-checkbox>
            <el-checkbox label="deluxe">豪华间</el-checkbox>
            <el-checkbox label="suite">套间</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="分配预览">
            <div class="allocation-preview">
              <div class="preview-stats">
                <div class="preview-item">
                  <span class="preview-label">待分配学生:</span>
                  <span class="preview-value">{{ getUnallocatedStudents().length }}</span>
                </div>
                <div class="preview-item">
                  <span class="preview-label">可用床位:</span>
                  <span class="preview-value">{{ availableBeds }}</span>
                </div>
                <div class="preview-item">
                  <span class="preview-label">预计分配:</span>
                  <span class="preview-value">{{ Math.min(getUnallocatedStudents().length, availableBeds) }}</span>
                </div>
              </div>
            </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAutoAllocationModal">取消</el-button>
          <el-button type="primary" @click="executeAutoAllocation">
            开始分配
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 手动分配对话框 -->
    <el-dialog v-model="showManualAllocationModal" title="✋ 手动分配宿舍" width="600px">
      <el-form :model="manualAllocationForm" label-width="100px">
        <el-form-item label="选择学生">
          <el-select v-model="manualAllocationForm.studentId" placeholder="选择学生" style="width: 100%;">
            <el-option 
              v-for="student in unallocatedStudents" 
              :key="student.id" 
              :value="student.id"
              :label="`${student.name} (${student.studentId})`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择房间">
          <el-select v-model="manualAllocationForm.roomId" placeholder="选择房间" style="width: 100%;">
            <el-option 
              v-for="room in availableRoomsList" 
              :key="room.id" 
              :value="room.id"
              :label="`${room.number} (${room.floor}楼) - ${room.availableBeds}个空床位`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择床位">
          <el-select v-model="manualAllocationForm.bedId" placeholder="选择床位" style="width: 100%;">
            <el-option 
              v-for="bed in availableBedsList" 
              :key="bed.id" 
              :value="bed.id"
              :label="`${bed.number} (${bed.position})`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
                v-model="manualAllocationForm.notes"
            type="textarea"
                placeholder="分配备注..."
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeManualAllocationModal">取消</el-button>
          <el-button type="primary" @click="executeManualAllocation">
            确认分配
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const gradeFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const showAutoAllocationModal = ref(false)
const showManualAllocationModal = ref(false)

// 自动分配表单
const autoAllocationForm = ref({
  strategy: 'random',
  grade: '',
  roomTypes: ['standard', 'deluxe']
})

// 手动分配表单
const manualAllocationForm = ref({
  studentId: '',
  roomId: '',
  bedId: '',
  notes: ''
})

// 模拟数据
const allocations = ref([
  {
    id: 1,
    student: { name: '张三', studentId: '2021001', grade: '2021', major: '计算机科学' },
    status: 'allocated',
    room: { number: '101', floor: 1 },
    bed: { number: 'A1' },
    allocatedAt: '2023-09-01'
  },
  {
    id: 2,
    student: { name: '李四', studentId: '2021002', grade: '2021', major: '软件工程' },
    status: 'allocated',
    room: { number: '101', floor: 1 },
    bed: { number: 'B1' },
    allocatedAt: '2023-09-01'
  },
  {
    id: 3,
    student: { name: '王五', studentId: '2022001', grade: '2022', major: '数据科学' },
    status: 'unallocated',
    room: null,
    bed: null,
    allocatedAt: null
  },
  {
    id: 4,
    student: { name: '赵六', studentId: '2022002', grade: '2022', major: '人工智能' },
    status: 'pending',
    room: { number: '102', floor: 1 },
    bed: { number: 'A2' },
    allocatedAt: '2023-09-02'
  }
])

const rooms = ref([
  { id: 1, number: '101', floor: 1, availableBeds: 2, type: 'standard' },
  { id: 2, number: '102', floor: 1, availableBeds: 1, type: 'standard' },
  { id: 3, number: '201', floor: 2, availableBeds: 4, type: 'deluxe' },
  { id: 4, number: '301', floor: 3, availableBeds: 3, type: 'suite' }
])

const beds = ref([
  { id: 1, roomId: 1, number: 'C1', position: 'C', status: 'available' },
  { id: 2, roomId: 1, number: 'D1', position: 'D', status: 'available' },
  { id: 3, roomId: 2, number: 'B2', position: 'B', status: 'available' },
  { id: 4, roomId: 3, number: 'A3', position: 'A', status: 'available' }
])

// 计算属性
const filteredAllocations = computed(() => {
  let filtered = allocations.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(allocation => 
      allocation.student.name.toLowerCase().includes(query) ||
      allocation.student.studentId.toLowerCase().includes(query)
    )
  }

  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(allocation => allocation.status === statusFilter.value)
  }

  // 年级过滤
  if (gradeFilter.value) {
    filtered = filtered.filter(allocation => allocation.student.grade === gradeFilter.value)
  }

  return filtered
})

const totalAllocations = computed(() => filteredAllocations.value.length)
const totalPages = computed(() => Math.ceil(totalAllocations.value / pageSize.value))

const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, start + 4)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

const totalStudents = computed(() => allocations.value.filter(a => a.status === 'unallocated').length)
const availableRooms = computed(() => rooms.value.filter(r => r.availableBeds > 0).length)
const availableBeds = computed(() => beds.value.filter(b => b.status === 'available').length)
const allocatedCount = computed(() => allocations.value.filter(a => a.status === 'allocated').length)

const unallocatedStudents = computed(() => 
  allocations.value.filter(a => a.status === 'unallocated').map(a => a.student)
)

const availableRoomsList = computed(() => 
  rooms.value.filter(r => r.availableBeds > 0)
)

const availableBedsList = computed(() => {
  if (!manualAllocationForm.value.roomId) return []
  return beds.value.filter(b => 
    b.roomId === parseInt(manualAllocationForm.value.roomId) && 
    b.status === 'available'
  )
})

// 方法
const getStatusText = (status) => {
  const statusMap = {
    unallocated: '未分配',
    allocated: '已分配',
    pending: '待确认'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const typeMap = {
    unallocated: 'info',
    allocated: 'success',
    pending: 'warning'
  }
  return typeMap[status] || 'info'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const refreshAllocations = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('刷新失败')
  } finally {
    loading.value = false
  }
}

const getUnallocatedStudents = () => {
  return allocations.value.filter(a => a.status === 'unallocated').map(a => a.student)
}

const viewAllocation = (allocation) => {
  console.log('查看分配:', allocation)
}

const allocateStudent = (allocation) => {
  manualAllocationForm.value.studentId = allocation.student.id
  showManualAllocationModal.value = true
}

const reallocateStudent = (allocation) => {
  console.log('重新分配:', allocation)
}

const cancelAllocation = (allocation) => {
  if (confirm(`确定要取消 ${allocation.student.name} 的分配吗？`)) {
    const index = allocations.value.findIndex(a => a.id === allocation.id)
    if (index > -1) {
      allocations.value[index] = {
        ...allocations.value[index],
        status: 'unallocated',
        room: null,
        bed: null,
        allocatedAt: null
      }
    }
  }
}

const executeAutoAllocation = () => {
  console.log('执行自动分配:', autoAllocationForm.value)
  // 实现自动分配逻辑
  closeAutoAllocationModal()
}

const executeManualAllocation = () => {
  console.log('执行手动分配:', manualAllocationForm.value)
  // 实现手动分配逻辑
  closeManualAllocationModal()
}

const closeAutoAllocationModal = () => {
  showAutoAllocationModal.value = false
  autoAllocationForm.value = {
    strategy: 'random',
    grade: '',
    roomTypes: ['standard', 'deluxe']
  }
}

const closeManualAllocationModal = () => {
  showManualAllocationModal.value = false
  manualAllocationForm.value = {
    studentId: '',
    roomId: '',
    bedId: '',
    notes: ''
  }
}

onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.allocations {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.student-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.student-name {
  font-weight: 500;
  color: #303133;
}

.student-id {
  font-size: 12px;
  color: #909399;
}

.room-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.room-number {
  font-weight: 500;
  color: #303133;
}

.bed-number {
  font-size: 12px;
  color: #909399;
}

.allocation-preview {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-top: 16px;
}

.preview-stats {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.preview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-label {
  color: #606266;
  font-size: 14px;
}

.preview-value {
  color: #303133;
  font-weight: 500;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .allocations {
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: stretch;
  }

  .search-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-section .el-input,
  .search-section .el-select {
    width: 100% !important;
  }
}
</style>
